package com.guqj.nio.netty.serialization.protobuf;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * @Title SubscribeClient
 * @Description netty protobuf客户端
 * @date 2016年11月17日
 */
public class SubscribeClient {

	/**
	 * @Description 连接服务端
	 * @param host
	 * @param port
	 * @throws InterruptedException
	 */
	public void connet(String host, int port) throws InterruptedException {
		EventLoopGroup group = new NioEventLoopGroup();

		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
					.handler(new ClientChannelInitializer());

			Channel c = b.connect(host, port).sync().channel();
			System.out.println(String.format("客户端已连接服务端：[%s:%s]", host, port));
			c.closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}

	class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(new ProtobufVarint32FrameDecoder());
			p.addLast(new ProtobufDecoder(SubscribeResProto.SubscribeRes.getDefaultInstance()));
			p.addLast(new ProtobufVarint32LengthFieldPrepender());
			p.addLast(new ProtobufEncoder());
			p.addLast(new SubscribeClientHandler());
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		new SubscribeClient().connet("localhost", 11013);
	}
}
